package cmd

import (
	"card/bootstrap"
	"card/pkg/app"
	"card/pkg/config"
	"card/pkg/server/http"
	"context"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var CmdServer = &cobra.Command{
	Use:   "server",
	Short: "Start web server",
	Run:   runWeb,
	Args:  cobra.NoArgs,
}

func runWeb(cmd *cobra.Command, args []string) {
	if app.IsLocal() {
		gin.SetMode(gin.DebugMode)
	}
	if app.IsTest() {
		gin.SetMode(gin.TestMode)
	}
	if app.IsPro() {
		gin.SetMode(gin.ReleaseMode)
	}
	router := gin.New()
	//go tool pprof -http=:1234 http://127.0.0.1:9533/sdebug/pprof/profile?seconds=30
	pprof.Register(router)
	// 初始化路由绑定
	bootstrap.SetupRoute(router)
	httpServer := http.RunWeb(router, config.GetString("app.http_port"))
	go func() {
		wsServer := bootstrap.SetUpSocket(router)
		wsServer.Serve()
		defer wsServer.Close()
	}()
	go func() {
		if err := httpServer.ListenAndServe(); err != nil {
			log.Fatal("http server start fail:", err)
		}
	}()
	log.Println("server is start")
	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := httpServer.Shutdown(ctx); err != nil {
		log.Fatal("http Server Shutdown:", err)
	}
	log.Println("Server exiting")
}
